package org.hxzon.demo.java.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {
    //服务器端的服务端口。

    public static void main(String[] args) {
        try {//已经连接上的客户端的序号。
            int number = 1;
            //建立服务器端倾听套接字。
            ServerSocket serverSocket = new ServerSocket(Config.port);
            System.out.println("Started: " + serverSocket);
            while (true) {
                //等待并接收请求，建立连接套接字。
                Socket clientSocket = serverSocket.accept();
                System.out.println("Connection " + number + " accepted: ");
                System.out.println(clientSocket);
                //启动一个线程来进行服务器端和客户端的数据传输。
                //主程序继续监听是否有请求到来。
                Thread t = new EchoThread(clientSocket, number);
                t.start();
                number++;
            }
            //serverSocket.close();
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }

    public static class EchoThread extends Thread {
        private Socket _clientSocket;
        int n;

        public EchoThread(Socket clientSocket, int number) {
            _clientSocket = clientSocket;
            n = number;
        }

        public void run() {
            try {//新建网络连接的输入流
                BufferedReader inSocket = new BufferedReader(new InputStreamReader(_clientSocket.getInputStream(), Config.encoding));
                //新建网络连接的自动刷新的输出流。
                PrintWriter outSocket = new PrintWriter(new BufferedWriter(new OutputStreamWriter(_clientSocket.getOutputStream(), Config.encoding)), true);
                System.out.println("Hello! Enter BYE to exit.");
                //回显客户端的输入。
                while (true) { //从网络连接读取一行，即接收客户端的数据。
                    String strReceive = inSocket.readLine();
                    //如果接收到的数据为空,则退出循环，关闭连接。
                    if (strReceive == null) {
                        break;
                    } else {
                        if (strReceive.trim().equals("BYE")) {
                            System.out.println("The client " + n + " entered BYE!");
                            System.out.println("Connection " + n + " will be closed!");
                            break;
                        }
                        System.out.println("Echo " + n + ": " + strReceive);
                        //向网络连接输出一行，即向客户端发送数据。
                        outSocket.println("Echo " + n + ": " + strReceive);
                    }
                }//end while
                _clientSocket.close();//关闭套接字
            }//end try
            catch (IOException e) {
                System.err.println(e.getMessage());
            }
        }//end run
    }//end EchoThread
}//end of EchoServer
